Stored Procedures [dbo].[asi_PostGLData]
Properties
PropertyValue
ANSI Nulls OnYes
Quoted Identifier OnYes
Parameters
NameData TypeMax Length (Bytes)
@postingDatachar(12)12
@userKeyuniqueidentifier16
@orgKeyuniqueidentifier16
@systemKeyuniqueidentifier16
@accessKeyuniqueidentifier16
SQL Script
/****** Object:  Stored Procedure dbo.asi_PostGLData    Script Date: 4/14/2005 1:41:42 PM ******/

/****** Object:  Stored Procedure dbo.asi_PostGLData    Script Date: 4/14/2005 8:41:06 AM ******/
CREATE                                                                                            PROCEDURE dbo.asi_PostGLData
@postingData as char(12),
@userKey uniqueidentifier = null,
@orgKey uniqueidentifier = null,
@systemKey uniqueidentifier = null,
@accessKey uniqueidentifier = null
AS
/*     This stored procedure will do the following:
(Note: The #tmpInvoice and #tmpPayments tables must be created appropriately by
the calling stored procedure before this stored proc. executes. Also, payment applications
must have been re-applied to the invoice distribution level.)
   1. If it is a batch of payments being posted, debit cash for all payments, and credit unearned income GL entries for unapplied payment amounts.
   2. Set up a cursor on the invoice data, with the payments data joined (outer joined on invoicedistributionkey).
   3. For each invoice distribution line:
        (** note: we check to make sure we're not processing another payment application
        to the same distribution line before creating Distribution, COGS, or inventory GL...)
    If we're posting invoices, debit unearned income for any payment
    applied to the distribution line.
    If the accounting method is CASH
        If there is a payment application to the distribution line
            credit income
            debit cost of goods sold
            credit inventory
            (since it is cash based, the latter two will be done proportionate to the percentage of the
            amount of income recognized, if it was only a partial payment and thus partially recognized income...)
        End If
    Else (ACCRUAL accounting method)
        If we're posting invoices
            credit income
            debit cost of goods sold
            credit inventory
        Else (we're posting payments)
            credit accounts receivable
        End If
    End If
    
    Get the next distribution line (could be just another application to
    the same line...)
    
    If we're posting invoices, and we finished processing a distribution line, debit accounts receivable
    for any unpaid balance on the line
   4. Copy the GL transactions created above (they are created in a temp table) to the GLTransaction and
   GLTransactionLine tables, grouping them into seperate transactions by source item key (the invoice or
   payment being posted) and financial unit.
   5. Update the amount recognized for income and cost on the invoice distribution lines.
   
   11/30/04 - pjr - Added SalesLocation stuff
   04/14/05 - rrk - Allow zero-amount monetary applications to create sales history
   12/29/05 - rrk - Major rework with schema changes.
   01/09/06    - rrk - Updates for GL transaction viewer (DT 2448):
                    - added contact key, batch number, description to #tmpTransaction
                    - added batch numbers, contact key, journal entry description, and
                      invoice line number to #tmpTransLine
                    - changed invocations of CreateTempGL for new arguments
                    - added sequence numbers for entries of specific types
*/

DECLARE @amount decimal(18,4)
DECLARE @distFinEntityKey uniqueidentifier
DECLARE @invFinEntityKey uniqueidentifier
DECLARE @paymentFinEntityKey uniqueidentifier
DECLARE @previousInvFinEntityKey uniqueidentifier
DECLARE @previousDistFinEntityKey uniqueidentifier
DECLARE @previousPmtFinEntityKey uniqueidentifier
DECLARE @invoiceKey uniqueidentifier
DECLARE @invoiceLineKey uniqueidentifier
DECLARE @invoiceDistKey uniqueidentifier
DECLARE @prevInvoiceDistKey uniqueidentifier
DECLARE @prevInvoiceLineNumber int
DECLARE @prevInvoiceKey uniqueidentifier
DECLARE @acctMethod nvarchar(50)
DECLARE @pmtKey uniqueidentifier
DECLARE @pmtAmt decimal(18,4)
DECLARE @pmtPercent decimal(18,4)
DECLARE @appliedAmt decimal(18,4)
DECLARE @unappliedAmt decimal(18,4)
DECLARE @extIncome decimal(18,4)
DECLARE @extCost decimal(18,4)
DECLARE @extIncomeRecog decimal(18,4)
DECLARE @extCostRecog decimal(18,4)
DECLARE @costToRecognize decimal(18,4)
DECLARE @unearnedIncAcctKey uniqueidentifier
DECLARE @deferredIncAcctKey uniqueidentifier
DECLARE @deferralTermsKey uniqueidentifier
DECLARE @incomeAcctKey uniqueidentifier
DECLARE @costAcctKey uniqueidentifier
DECLARE @inventoryAcctKey uniqueidentifier
DECLARE @ARAcctKey uniqueidentifier
DECLARE @defaultCashAcctKey uniqueidentifier
DECLARE @cashAcctKey uniqueidentifier
DECLARE @currencyVarianceAcctKey uniqueidentifier
DECLARE @earlyPmtDiscountAcctKey uniqueidentifier
DECLARE @previousARAcctKey uniqueidentifier
DECLARE @previousExtIncome decimal(18,4)
DECLARE @previousProductKey uniqueidentifier
DECLARE @accumAppliedAmt decimal(18,4)
DECLARE @discountTaken decimal(18,4)
DECLARE @transDate datetime
DECLARE @previousTransDate datetime
DECLARE @dueFromAcctKey uniqueidentifier
DECLARE @dueToAcctKey uniqueidentifier
DECLARE @sourceCodeKey uniqueidentifier
DECLARE @orevSourceCodeKey uniqueidentifier
DECLARE @arAmount decimal(18,4)
DECLARE @journalTypeInvoice int
DECLARE @journalTypePayment int
DECLARE @journalType int
DECLARE @glDistributionType nvarchar(50)
DECLARE @incomeAccountToUseKey uniqueidentifier
DECLARE @targetAccountKey uniqueidentifier
DECLARE @journalTypeCreditInv int
DECLARE @journalTypeDebitInv int
DECLARE @glTypeDistribution nvarchar(50)
DECLARE @glTypeAccountsReceivable nvarchar(50)
DECLARE @glTypeCash nvarchar(50)
DECLARE @glTypeUnearnedIncome nvarchar(50)
DECLARE @glTypeEarlyPaymentDiscount nvarchar(50)
DECLARE @glTypeDeferredIncome nvarchar(50)
DECLARE @glTypeInventory nvarchar(50)
DECLARE @glTypeCostOfGoodsSold nvarchar(50)
DECLARE @glTypeInventoryAdjustment nvarchar(50)
DECLARE @glTypeDamagedGoods nvarchar(50)
DECLARE @glTypeDueToDueFrom nvarchar(50)
DECLARE @invTypeStandard nchar(1)
DECLARE @invTypeCredit nchar(1)
DECLARE @invTypeDebit nchar(1)
DECLARE @invTypeReturn nchar(1)
DECLARE @invType nchar(1)
DECLARE @distDescription nchar(20)
DECLARE @pmtFiscalPeriod int
DECLARE @invFiscalPeriod int
DECLARE @distFiscalPeriod int
DECLARE @firstMonthFiscal_PmtEntity int
DECLARE @firstMonthFiscal_InvEntity int
DECLARE @firstMonthFiscal_DistEntity int
DECLARE @reApplyingPostedItem bit
DECLARE @batchItemStatus int
DECLARE @batchStatusOpen int
DECLARE @batchStatusCompleted int
DECLARE @batchStatusError int
DECLARE @orderTypeKey uniqueidentifier
DECLARE @responseMediaCode nvarchar(20)
DECLARE @priceSheetKey uniqueidentifier
DECLARE @genSalesHistory bit
DECLARE @extendedCost decimal(18,4)
DECLARE @warehouseKey uniqueidentifier
DECLARE @orderNumber nvarchar(50)
DECLARE @billToContactKey uniqueidentifier
DECLARE @shipToContactKey uniqueidentifier
DECLARE @soldToContactKey uniqueidentifier
DECLARE @payorContactKey uniqueidentifier
DECLARE @orderDate datetime
DECLARE @productKey uniqueidentifier
DECLARE @undiscountedExtendedPrice decimal(18,4)
DECLARE @uomKey uniqueidentifier
DECLARE @quantitySold  decimal(18,4)
DECLARE @tstCount int
DECLARE @commissionPlanKey uniqueidentifier
DECLARE @salesTeamGroupKey uniqueidentifier
DECLARE @salesLocationKey  uniqueidentifier
DECLARE @isPledge bit
DECLARE @invoiceNumber nvarchar(50)
DECLARE @invoiceLineNumber int
DECLARE @glEntryType nvarchar(50)
DECLARE @sequenceNumber int
DECLARE @description nvarchar(50)
DECLARE @transLineKey uniqueidentifier
DECLARE @transKey uniqueidentifier
DECLARE @prevTransKey uniqueidentifier
DECLARE @accountKey uniqueidentifier
DECLARE @batchKey uniqueidentifier
DECLARE @prevBillToContactKey uniqueidentifier
DECLARE @originatingBatchNumber nvarchar(50)
DECLARE @finalBatchNumber nvarchar(50)
DECLARE @prevOriginatingBatchNumber nvarchar(50)
DECLARE @prevFinalBatchNumber nvarchar(50)
DECLARE @journalEntryDescription nvarchar(50)
DECLARE @prevJournalEntryDescription nvarchar(50)
DECLARE @sequenceNumberCash int
DECLARE @sequenceNumberUI int
DECLARE @sequenceNumberAR int
DECLARE @sequenceNumberDist int
DECLARE @sequenceNumberEPD int
DECLARE @sequenceNumberDTDF int
DECLARE @appliedPaymentKey uniqueidentifier
DECLARE @unearnedIncomeRecorded int
SET @invTypeStandard = 'S'
SET @invTypeCredit = 'C'
SET @invTypeDebit = 'D'
SET @journalTypeInvoice = 1
SET @journalTypePayment =  3
SET @journalTypeCreditInv =  4
SET @journalTypeDebitInv =  5
SET @glTypeDistribution = 'Distribution'
SET @glTypeAccountsReceivable =  'AccountsReceivable'
SET @glTypeCash = 'Cash'
SET @glTypeUnearnedIncome = 'UnearnedIncome'
SET @glTypeEarlyPaymentDiscount = 'EarlyPaymentDiscount'
SET @glTypeDeferredIncome = 'DeferredIncome'
SET @glTypeInventory = 'Inventory'
SET @glTypeCostOfGoodsSold = 'CostOfGoodsSold'
SET @glTypeInventoryAdjustment = 'InventoryAdjustment'
SET @glTypeDamagedGoods = 'DamagedGoods'
SET @glTypeDueToDueFrom = 'DueToDueFrom'
SET @batchStatusOpen = 0
SET @batchStatusCompleted = 1
SET @batchStatusError = 2
SET @pmtAmt = 0
SET @pmtPercent = 0
SET @appliedAmt = 0
SET @extIncome = 0
SET @extCost = 0
SET @extIncomeRecog = 0
SET @extCostRecog = 0
SET @costToRecognize = 0
SET @previousExtIncome = 0
SET @accumAppliedAmt = 0
IF EXISTS (select * from dbo.sysobjects where id = object_id('dbo.#tmpTransLine'))
DROP TABLE dbo.#tmpTransLine
IF EXISTS (select * from dbo.sysobjects where id = object_id('dbo.#tmpTransaction'))
DROP TABLE dbo.#tmpTransaction
/* Cache the financial units data... */
DECLARE @FinEntitys TABLE
(FinancialEntityKey uniqueidentifier PRIMARY KEY, DefaultCashGLAccountKey uniqueidentifier, DefaultUnearnedIncomeGLAccountKey uniqueidentifier,
IsDefault bit, DefaultEarlyPmtDiscountGLAccountKey uniqueidentifier, DefaultCurrencyVarianceGLAccountKey uniqueidentifier, FirstMonthFiscalYear int)
INSERT INTO @FinEntitys
(FinancialEntityKey, IsDefault, FirstMonthFiscalYear)
SELECT FinancialEntityKey, IsDefault, FirstMonthFiscalYear
FROM FinancialEntity
UPDATE @FinEntitys SET DefaultCashGLAccountKey = pga.GLAccountKey
FROM @FinEntitys fes INNER JOIN ProductGLAccount pga
ON pga.ParentKey = fes.FinancialEntityKey
WHERE pga.GLAccountPurposeCode = 'CAS'
UPDATE @FinEntitys SET DefaultUnearnedIncomeGLAccountKey = pga.GLAccountKey
FROM @FinEntitys fes INNER JOIN ProductGLAccount pga
ON pga.ParentKey = fes.FinancialEntityKey
WHERE pga.GLAccountPurposeCode = 'UIN'
UPDATE @FinEntitys SET DefaultEarlyPmtDiscountGLAccountKey = pga.GLAccountKey
FROM @FinEntitys fes INNER JOIN ProductGLAccount pga
ON pga.ParentKey = fes.FinancialEntityKey
WHERE pga.GLAccountPurposeCode = 'EPD'
UPDATE @FinEntitys SET DefaultCurrencyVarianceGLAccountKey = pga.GLAccountKey
FROM @FinEntitys fes INNER JOIN ProductGLAccount pga
ON pga.ParentKey = fes.FinancialEntityKey
WHERE pga.GLAccountPurposeCode = 'CUV'
DECLARE @duetoduefrom TABLE
(FromFinancialEntityKey uniqueidentifier, ToFinancialEntityKey uniqueidentifier, FromFinEntityGLAccountKey uniqueidentifier,
ToFinEntityGLAccountKey uniqueidentifier)
INSERT INTO @duetoduefrom
SELECT FromFinancialEntityKey, ToFinancialEntityKey, FromFinEntityGLAccountKey, ToFinEntityGLAccountKey
FROM FinancialEntityDueTo
CREATE TABLE #tmpTransaction
(TransactionKey uniqueidentifier DEFAULT NEWID(), InvoiceKey uniqueidentifier, PaymentKey uniqueidentifier,
FinEntityKey uniqueidentifier, TransDate datetime, JournalEntryTypeCode int, FiscalPeriod int,
Description nvarchar(50), FinalBatchNumber nvarchar(50), OriginatingBatchNumber nvarchar(50), ContactKey uniqueidentifier)
CREATE TABLE #tmpTransLine
(TransLineKey uniqueidentifier DEFAULT NEWID(), AccountKey uniqueidentifier, FinEntityKey uniqueidentifier,
Amount decimal(18,4), InvoiceKey uniqueidentifier,  PaymentKey uniqueidentifier, Description nvarchar(50),
ProductKey uniqueidentifier, TransDate datetime, DeferralTermsKey uniqueidentifier, TargetGLAccountKey uniqueidentifier,
InvoiceLineKey uniqueidentifier, GLEntryType nvarchar(50),  JournalEntryTypeCode int,
FiscalPeriod int, TransactionSequenceNumber int, OriginatingBatchNumber nvarchar(50), FinalBatchNumber nvarchar(50),
BillToContactKey uniqueidentifier, JournalEntryDescription nvarchar(50), InvoiceLineNumber int)

SELECT @distFinEntityKey = FinancialEntityKey, @invFinEntityKey = FinancialEntityKey, @paymentFinEntityKey = FinancialEntityKey,
@unearnedIncAcctKey = DefaultUnearnedIncomeGLAccountKey, @defaultCashAcctKey = DefaultCashGLAccountKey,
@firstMonthFiscal_PmtEntity = FirstMonthFiscalYear
FROM @FinEntitys WHERE IsDefault = 1
SET @previousDistFinEntityKey = @distFinEntityKey
SET @previousInvFinEntityKey = @invFinEntityKey
SET @previousPmtFinEntityKey = @paymentFinEntityKey
SELECT @firstMonthFiscal_PmtEntity = FirstMonthFiscalYear
FROM @FinEntitys WHERE FinancialEntityKey = @distFinEntityKey
SELECT @firstMonthFiscal_InvEntity = FirstMonthFiscalYear
FROM @FinEntitys WHERE FinancialEntityKey = @distFinEntityKey
SELECT @firstMonthFiscal_DistEntity = FirstMonthFiscalYear
FROM @FinEntitys WHERE FinancialEntityKey = @distFinEntityKey
/* If we're posting new payments, debit cash for all payments, */
/* and credit unearned income for unapplied payment amounts... */
IF UPPER(@postingData) = 'PAYMENTS'
BEGIN
    SET @previousPmtFinEntityKey = NEWID()
    SET @productKey =  null
    DECLARE Get_Payments cursor for
    SELECT SrcPaymentKey, Amount, Amount - SUM(CASE WHEN InvoiceDistributionKey is null THEN 0 ELSE ISNULL(AppliedAmount,0) END),
    FinancialEntityKey, PaymentDate, SUM(DiscountTaken), BatchLineStatusCode, MAX(FinalBatchNumber), MAX(Description), ContactKey,
    CashGLAccountKey
    FROM #tmpPayments
    GROUP BY SrcPaymentKey, FinancialEntityKey, Amount, PaymentDate, BatchLineStatusCode, ContactKey, CashGLAccountKey
    ORDER BY PaymentDate, BatchLineStatusCode DESC
    OPEN Get_Payments
    FETCH NEXT FROM Get_Payments into @pmtKey,@pmtAmt, @unappliedAmt, @paymentFinEntityKey, @transDate, @discountTaken, @batchItemStatus,
    @finalBatchNumber, @journalEntryDescription, @payorContactKey, @cashAcctKey
    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF @batchItemStatus = @batchStatusCompleted
            OR @pmtKey = @appliedPaymentKey
        BEGIN
            -- This payment has already been posted; we do not want to debit cash and
            -- credit unearned income because this happened when the payment posted.
            SET @reApplyingPostedItem = 1
            SET @appliedPaymentKey = @pmtKey
            GOTO nextPayment
        END
        ELSE
        BEGIN
            SET @reApplyingPostedItem = 0
            SET @appliedPaymentKey = null
        END
        SET @unappliedAmt = @unappliedAmt + @discountTaken -- rrk 11Jan06    
        IF @paymentFinEntityKey != @previousPmtFinEntityKey
            SELECT @firstMonthFiscal_PmtEntity = FirstMonthFiscalYear, @unearnedIncAcctKey = DefaultUnearnedIncomeGLAccountKey,
            @defaultCashAcctKey = DefaultCashGLAccountKey, @earlyPmtDiscountAcctKey = DefaultEarlyPmtDiscountGLAccountKey,
            @currencyVarianceAcctKey = DefaultCurrencyVarianceGLAccountKey
            FROM @FinEntitys WHERE FinancialEntityKey = @paymentFinEntityKey
            
        SET @pmtFiscalPeriod = dbo.CalculateFiscalPeriod(@transDate, @firstMonthFiscal_PmtEntity)
        -- if the view did not supply a cash account key (from the payment method or payment method's
        -- financial entity, use the default.
        IF @cashAcctKey IS NULL
            SET @cashAcctKey = @defaultCashAcctKey
            /* Cash for payment amount: */
            /* Debit cash asset account in payment journal */
        --SET @amount = @pmtAmt - @discountTaken    -- rrk 11Jan06 replaced with line below
        SET @amount = @pmtAmt
        EXEC asi_CreateTempGL @cashAcctKey, @amount, null, @pmtKey, @productKey, @paymentFinEntityKey, @transDate,
        @journalTypePayment, @pmtFiscalPeriod, @glTypeCash, 'Cash', null, null, null, 1, '', @finalBatchNumber,
        @payorContactKey, @journalEntryDescription, 0
        
        IF ABS(@unappliedAmt) > 0
        BEGIN
                /* Unearned income: */
                /* Credit unearned income liability account in payment journal */
            SET @amount = @unappliedAmt * -1
            EXEC asi_CreateTempGL @unearnedIncAcctKey, @amount, null, @pmtKey, @productKey, @paymentFinEntityKey,@transDate,
            @journalTypePayment, @pmtFiscalPeriod,
            @glTypeUnearnedIncome,'Unearned Income', null, null, null, 2, '', @finalBatchNumber,
            @payorContactKey, @journalEntryDescription, 0
            
        END
        UPDATE PaymentMain set BatchLineStatusCode = @batchStatusCompleted where PaymentKey = @pmtKey
        SET @previousPmtFinEntityKey = @paymentFinEntityKey
        nextPayment:
        FETCH NEXT FROM Get_Payments into @pmtKey, @pmtAmt, @unappliedAmt, @paymentFinEntityKey, @transDate,
        @discountTaken, @batchItemStatus, @finalBatchNumber, @journalEntryDescription, @payorContactKey, @cashAcctKey
    END
    CLOSE Get_Payments
    DEALLOCATE Get_Payments
END
/* Now set up cursor on invoice distribution lines, joined with any applied payments, in order to */
/* post GL entries for new invoices (if we're posting invoices) & payment applications (particularly for */
/* cash based invoices where payments drive recognition of income, etc.). */
/* Get either the PaymentDate or InvoiceDate for setting the transaction date, depending on the type of posting... */
IF UPPER(@postingData) = 'PAYMENTS'
BEGIN
    DECLARE GetInvoiceDistribution cursor for
    SELECT ti.InvoiceKey, ti.InvoiceLineKey, ti.InvoiceDistributionKey,
        ti.AccountingMethodCode, ISNULL(ti.FinancialEntityKey, tp.FinancialEntityKey), ti.DistFinancialEntityKey, ISNULL(ti.ExtendedIncome,0),
        ISNULL(ti.ExtendedIncomeRecognized,0), ti.IncomeGLAccountKey, ti.ARGLAccountKey,
        ti.DeferredIncomeGLAccountKey, ISNULL(tp.Amount,0),
        ISNULL(tp.AppliedAmount,0), tp.SrcPaymentKey, tp.PaymentDate, PmtFinEntityKey = tp.FinancialEntityKey,
        tp.DiscountTaken, ti.DeferralTermsKey, ti.SourceCodeKey, ti.InvoiceTypeCode, tp.BatchLineStatusCode,
        ti.OrderTypeKey, ti.ResponseMediaCode, ti.PriceSheetKey, ti.WarehouseKey,
        ti.GeneratesSalesHistoryFlag, ti.ExtendedCost, ti.OrderNumber, ti.OrderTypeKey,
        ti.OrderDate, ti.BillToContactKey, ti.ShipToContactKey, ti.SoldToContactKey,
        ti.ProductKey, ti.UndiscountedExtendedPrice, ti.UomKey, ti.QuantitySold, ti.CommissionPlanKey, ti.SalesTeamGroupKey,
        ti.SalesLocationKey, ti.IsPledge, ti.InvoiceLineNumber, ti.InvoiceNumber, ti.Description, ti.OriginatingBatchNumber,
        ti.FinalBatchNumber
    FROM #tmpInvoice ti
    INNER JOIN #tmpPayments tp ON tp.InvoiceDistributionKey = ti.InvoiceDistributionKey
    WHERE ApplyingCredit = 0  /* <-- Ignore invoices that are just having new credit invoices applied... */
    AND ti.InvoiceDistributionKey is not null
    ORDER BY ti.InvoiceKey, ti.InvoiceLineNumber, ti.InvoiceDistributionKey, tp.PaymentDate,
        tp.BatchLineStatusCode DESC
    /* WHERE LineAmountRemaining > 0  ...? */
END
ELSE IF UPPER(@postingData) = 'INVOICES'
BEGIN
    DECLARE GetInvoiceDistribution cursor for
    SELECT ti.InvoiceKey, ti.InvoiceLineKey, ti.InvoiceDistributionKey,
        ti.AccountingMethodCode, ti.FinancialEntityKey, ti.DistFinancialEntityKey, ISNULL(ti.ExtendedIncome,0),
        ISNULL(ti.ExtendedIncomeRecognized,0), ti.IncomeGLAccountKey, ti.ARGLAccountKey,
        ti.DeferredIncomeGLAccountKey, ISNULL(tp.Amount,0),
        ISNULL(tp.AppliedAmount,0), tp.SrcPaymentKey, ti.InvoiceDate, PmtFinEntityKey = ISNULL(tp.FinancialEntityKey,ti.FinancialEntityKey) ,
        tp.DiscountTaken, ti.DeferralTermsKey, ti.SourceCodeKey, ti.InvoiceTypeCode, tp.BatchLineStatusCode,
        ti.OrderTypeKey, ti.ResponseMediaCode, ti.PriceSheetKey, ti.WarehouseKey,
        ti.GeneratesSalesHistoryFlag, ti.ExtendedCost, ti.OrderNumber, ti.OrderTypeKey,
        ti.OrderDate, ti.BillToContactKey, ti.ShipToContactKey, ti.SoldToContactKey,
        ti.ProductKey, ti.UndiscountedExtendedPrice, ti.UomKey, ti.QuantitySold, ti.CommissionPlanKey,
        ti.SalesTeamGroupKey, ti.SalesLocationKey, ti.IsPledge, ti.InvoiceLineNumber, ti.InvoiceNumber,
        ti.Description, ti.OriginatingBatchNumber, ti.FinalBatchNumber
    FROM #tmpInvoice ti
    LEFT OUTER JOIN #tmpPayments tp ON tp.InvoiceDistributionKey = ti.InvoiceDistributionKey
    WHERE ApplyingCredit = 0  /* <-- Ignore invoices that are just having new credit invoices applied... */
    AND ti.InvoiceDistributionKey is not null
    ORDER BY ti.InvoiceKey, ti.InvoiceLineNumber, ti.InvoiceDistributionKey, tp.PaymentDate,
        tp.BatchLineStatusCode DESC
    /* WHERE LineAmountRemaining > 0  ...? */
END
SET @previousDistFinEntityKey = NEWID()
SET @prevInvoiceDistKey = NEWID()
SET @previousInvFinEntityKey = NEWID()
SET @prevBillToContactKey = NEWID()
SET @prevInvoiceKey = NEWID()
SET @prevJournalEntryDescription = ''
SET @appliedPaymentKey = null
OPEN GetInvoiceDistribution
FETCH next from GetInvoiceDistribution into @invoiceKey, @invoiceLineKey, @invoiceDistKey, @acctMethod,
@invFinEntityKey, @distFinEntityKey, @extIncome, @extIncomeRecog, @incomeAcctKey, @ARAcctKey, @deferredIncAcctKey,
@pmtAmt, @appliedAmt, @pmtKey, @transDate, @paymentFinEntityKey, @discountTaken, @deferralTermsKey, @sourceCodeKey,
@invType, @batchItemStatus, @orderTypeKey, @responseMediaCode, @priceSheetKey, @warehouseKey, @genSalesHistory, @extendedCost,
@orderNumber, @orderTypeKey, @orderDate, @billToContactKey, @shipToContactKey, @soldToContactKey, @productKey, @undiscountedExtendedPrice,
@uomKey, @quantitySold, @commissionPlanKey, @salesTeamGroupKey, @salesLocationKey, @isPledge, @invoiceLineNumber, @invoiceNumber,
@journalEntryDescription, @originatingBatchNumber, @finalBatchNumber
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @unearnedIncomeRecorded = 0
    IF @batchItemStatus = @batchStatusCompleted
            OR @pmtKey = @appliedPaymentKey
    BEGIN
        SET @reApplyingPostedItem = 1
        SET @appliedPaymentKey = @pmtKey
    END    
    ELSE
    BEGIN
        SET @reApplyingPostedItem = 0
        SET @appliedPaymentKey = null
    END
    IF @appliedAmt > 0 AND @pmtKey is null  /* This is a credit invoice application - skip it. */
        GOTO next_record
    IF UPPER(@postingData) = 'PAYMENTS' OR UPPER(@postingData) = 'APPLICATIONS'
        SET @journalType = @journalTypePayment
    ELSE IF UPPER(@postingData) = 'INVOICES'
    BEGIN
        IF @invType = @invTypeStandard
            SET @journalType = @journalTypeInvoice
        ELSE IF @invType = @invTypeCredit
            SET @journalType = @journalTypeCreditInv
        ELSE IF @invType = @invTypeDebit
            SET @journalType = @journalTypeDebitInv
    END
    /* Reset the accumulated applied amount counter if we have a new invoice distribution line */
    IF @invoiceDistKey != @prevInvoiceDistKey
        SET @accumAppliedAmt = 0
    
    IF @paymentFinEntityKey != @previousPmtFinEntityKey
        SELECT @firstMonthFiscal_PmtEntity = FirstMonthFiscalYear, @unearnedIncAcctKey = DefaultUnearnedIncomeGLAccountKey,
        @defaultCashAcctKey = DefaultCashGLAccountKey, @earlyPmtDiscountAcctKey = DefaultEarlyPmtDiscountGLAccountKey,
        @currencyVarianceAcctKey = DefaultCurrencyVarianceGLAccountKey
        FROM @FinEntitys WHERE FinancialEntityKey = @paymentFinEntityKey
    IF @invFinEntityKey != @previousInvFinEntityKey
        SELECT @firstMonthFiscal_InvEntity = FirstMonthFiscalYear
        FROM @FinEntitys WHERE FinancialEntityKey = @invFinEntityKey
    IF @distFinEntityKey != @previousDistFinEntityKey
        SELECT @firstMonthFiscal_DistEntity = FirstMonthFiscalYear
        FROM @FinEntitys WHERE FinancialEntityKey = @distFinEntityKey
    SET @pmtFiscalPeriod = dbo.CalculateFiscalPeriod(@transDate, @firstMonthFiscal_PmtEntity)
    SET @invFiscalPeriod = dbo.CalculateFiscalPeriod(@transDate, @firstMonthFiscal_InvEntity)
    SET @distFiscalPeriod = dbo.CalculateFiscalPeriod(@transDate, @firstMonthFiscal_DistEntity)
    IF ABS(@appliedAmt) > 0 AND @appliedAmt is not null
        SET @pmtPercent = ABS(@appliedAmt) / @extIncome
    IF @invoiceKey != @prevInvoiceKey
    BEGIN
        SET @sequenceNumberCash = 1
        SET @sequenceNumberUI = 1
        SET @sequenceNumberAR = 1
        SET @sequenceNumberDist = 1
        SET @sequenceNumberEPD = 1
        SET @sequenceNumberDTDF = 1
    END

    IF UPPER(@acctMethod) = 'C'
    BEGIN
        IF @deferredIncAcctKey is not null
        BEGIN
            SET @glDistributionType = @glTypeDeferredIncome
            SET @distDescription = 'Deferred Income'
            SET @incomeAccountToUseKey = @deferredIncAcctKey
            SET @targetAccountKey = @incomeAcctKey
        END
        ELSE
        BEGIN
            SET @glDistributionType = @glTypeDistribution
            SET @distDescription = 'Distribution'
            SET @incomeAccountToUseKey = @incomeAcctKey
            SET @targetAccountKey = null
        END
        -- if there is no payment key, nothing to do for cash-based invoice.
        IF ABS(@appliedAmt) >= 0 AND @pmtKey is not null
        BEGIN
                /* Distribution: */
                /* Credit distribution income account in payment (?) journal */
            SET @amount = @appliedAmt * -1
            EXEC asi_CreateTempGL @incomeAccountToUseKey, @amount, @invoiceKey, @pmtKey, @productKey, @distFinEntityKey, @transDate,
            @journalType, @distFiscalPeriod,@glDistributionType,@distDescription, @invoiceLineKey,
            @deferralTermsKey,@targetAccountKey, @sequenceNumberDist, @originatingBatchNumber,
            @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
            SET @sequenceNumberDist = @sequenceNumberDist + 1

            UPDATE InvoiceDistribution SET ExtendedIncomeRecognized = ExtendedIncomeRecognized + @appliedAmt WHERE InvoiceDistributionKey = @invoiceDistKey
            
            IF @reApplyingPostedItem = 1
            BEGIN
                /* Unearned income: */
                /* Debit unearned income liability account in payment (?) journal */
                SET @amount = @appliedAmt - @discountTaken
                EXEC asi_CreateTempGL @unearnedIncAcctKey, @amount, @invoiceKey, @pmtKey, @productKey, @paymentFinEntityKey, @transDate,
                @journalType, @pmtFiscalPeriod,
                @glTypeUnearnedIncome,'Unearned Income', null, null, null, @sequenceNumberUI,
                @originatingBatchNumber, @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
                SET @sequenceNumberUI = @sequenceNumberUI + 1
                SET @unearnedIncomeRecorded = 1


            END
            IF @discountTaken > 0
            BEGIN
                    /* Early payment discount account */
                    /* Debit (?) discount account in payment (?) journal */
                SET @amount = @discountTaken
                EXEC asi_CreateTempGL @earlyPmtDiscountAcctKey,@amount,@invoiceKey, @pmtKey, @productKey, @paymentFinEntityKey, @transDate,
                @journalType, @pmtFiscalPeriod,
                @glTypeEarlyPaymentDiscount,'Early Payment Discount', null, null, null, @sequenceNumberEPD,
                @originatingBatchNumber, @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
                SET @sequenceNumberEPD = @sequenceNumberEPD + 1

            END
        END
        -- We want to generate sales history even if we don't have a payment key; this is done to
        -- make sure sales history is generated for no-price promotions.
        IF @glDistributionType = @glTypeDistribution AND @genSalesHistory = 1
            BEGIN
            SET @amount = @appliedAmt * -1
            EXEC asi_CreateSalesHistory @amount, @transDate, @sourceCodeKey, @orderTypeKey, @orderNumber,
                        @responseMediaCode, @priceSheetKey, @extendedCost, @warehouseKey, @invType,
                        @billToContactKey,@shipToContactKey,@soldToContactKey, @orderDate, @productKey,
                        @quantitySold, @undiscountedExtendedPrice, @uomKey, @userKey, @systemKey,
                        @accessKey, @commissionPlanKey, @salesTeamGroupKey, @salesLocationKey, @isPledge,
                        @invoiceLineNumber, @invoiceNumber
            END
    END
    ELSE /* (Accrual invoice) */
    BEGIN
                            /* (we may have multiple payments applied to a single
                            distribution line - if so, don't create GL twice...(?) */

        IF UPPER(@postingData) = 'INVOICES'    /*  AND @invoiceDistKey != @prevInvoiceDistKey */
        BEGIN
            IF ABS(@extIncome) >= 0

            BEGIN
                IF @deferredIncAcctKey is not null
                BEGIN
                    SET @glDistributionType = @glTypeDeferredIncome
                    SET @distDescription = 'Deferred Income'
                    SET @incomeAccountToUseKey = @deferredIncAcctKey
                    SET @targetAccountKey = @incomeAcctKey
                END
                ELSE
                BEGIN
                    SET @glDistributionType = @glTypeDistribution
                    SET @distDescription = 'Distribution'
                    SET @incomeAccountToUseKey = @incomeAcctKey
                    SET @targetAccountKey = null
                END
                IF @invoiceDistKey != @prevInvoiceDistKey
                BEGIN
                    /* Income: */
                    /* Credit distribution income account in sales journal */
                    SET @amount = @extIncome * -1
                    EXEC asi_CreateTempGL @incomeAccountToUseKey,@amount,@invoiceKey, @pmtKey, @productKey, @distFinEntityKey,@transDate,
                    @journalType, @distFiscalPeriod,@glDistributionType,@distDescription, @invoiceLineKey,
                    @deferralTermsKey, @targetAccountKey, @sequenceNumberDist, @originatingBatchNumber,
                    @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
                    SET @sequenceNumberDist = @sequenceNumberDist + 1
                    IF @glDistributionType = @glTypeDistribution AND @genSalesHistory = 1
                    BEGIN
                        EXEC asi_CreateSalesHistory @amount, @transDate, @sourceCodeKey, @orderTypeKey, @orderNumber,
                            @responseMediaCode, @priceSheetKey, @extendedCost, @warehouseKey, @invType,
                            @billToContactKey,@shipToContactKey,@soldToContactKey, @orderDate, @productKey,
                            @quantitySold, @undiscountedExtendedPrice, @uomKey, @userKey, @systemKey,
                            @accessKey, @commissionPlanKey, @salesTeamGroupKey, @salesLocationKey, @isPledge,
                            @invoiceLineNumber, @invoiceNumber
                    END

                    UPDATE InvoiceDistribution SET ExtendedIncomeRecognized = ExtendedIncomeRecognized + @extIncome WHERE InvoiceDistributionKey = @invoiceDistKey
                END

                IF ABS(@appliedAmt) > 0 AND @discountTaken > 0
                BEGIN
                    /* Early payment discount account */
                    /* Debit (?) discount account in sales journal */
                    SET @amount = @discountTaken
                    EXEC asi_CreateTempGL @earlyPmtDiscountAcctKey,@amount,@invoiceKey, @pmtKey, @productKey, @distFinEntityKey, @transDate,
                    @journalType, @distFiscalPeriod,
                    @glTypeEarlyPaymentDiscount,'Early Payment Discount', null, null, null, @sequenceNumberEPD,
                    @originatingBatchNumber, @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
                    SET @sequenceNumberEPD = @sequenceNumberEPD + 1


                END
            END
        END
        ELSE IF UPPER(@postingData) = 'PAYMENTS' AND ABS(@appliedAmt) > 0
        BEGIN
            /* AR: */
            /* Credit AR asset account in payment journal */
            SET @amount = @appliedAmt * -1
            EXEC asi_CreateTempGL @ARAcctKey,@amount,@invoiceKey, @pmtKey, @productKey, @invFinEntityKey, @transDate,
            @journalType, @invFiscalPeriod,
            @glTypeAccountsReceivable,'AR', null, null, null, @sequenceNumberAR, @originatingBatchNumber,
            @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
                    SET @sequenceNumberAR = @sequenceNumberAR + 1


            IF @reApplyingPostedItem = 1
            BEGIN
                /* Unearned income: */
                /* Debit Unearned income liability account in payment journal */
                SET @amount = @appliedAmt - @discountTaken
                EXEC asi_CreateTempGL @unearnedIncAcctKey,@amount,@invoiceKey, @pmtKey, @productKey, @paymentFinEntityKey, @transDate,
                @journalType, @pmtFiscalPeriod,
                @glTypeUnearnedIncome,'Unearned Income', null, null, null, @sequenceNumberUI,
                @originatingBatchNumber, @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
                SET @sequenceNumberUI = @sequenceNumberUI + 1


            END
            IF @discountTaken > 0
            BEGIN
                /* Early payment discount account */
                /* Debit (??) discount account in payment journal */
                SET @amount = @appliedAmt - @discountTaken
                SET @amount = @discountTaken
                EXEC asi_CreateTempGL @earlyPmtDiscountAcctKey,@amount,@invoiceKey, @pmtKey, @productKey, @invFinEntityKey,@transDate,
                @journalType, @invFiscalPeriod,
                @glTypeEarlyPaymentDiscount,'Early Payment Discount', null, null, null, @sequenceNumberEPD,
                @originatingBatchNumber, @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
                SET @sequenceNumberEPD = @sequenceNumberEPD + 1


            END
            /* DueToDueFrom: */
            IF @invFinEntityKey !=  @paymentFinEntityKey
            BEGIN
                SELECT @dueFromAcctKey = FromFinEntityGLAccountKey, @dueToAcctKey = ToFinEntityGLAccountKey
                FROM @duetoduefrom WHERE FromFinancialEntityKey = @paymentFinEntityKey
    
                IF @dueFromAcctKey is not null AND @dueToAcctKey is not null
                BEGIN
                    /* Credit DueTo account in payment journal */
                    SET @amount = @appliedAmt * -1
                    EXEC asi_CreateTempGL @dueFromAcctKey,@amount,@invoiceKey, @pmtKey, @productKey, @paymentFinEntityKey, @transDate,
                    @journalType, @pmtFiscalPeriod,
                    @glTypeDueToDueFrom,'DueTo', null, null, null, @sequenceNumberDTDF, @originatingBatchNumber,
                    @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
                    SET @sequenceNumberDTDF = @sequenceNumberDTDF + 1


                    /* Debit DueFrom account in payment journal */
                    SET @amount = @appliedAmt
                    EXEC asi_CreateTempGL @dueToAcctKey,@amount,@invoiceKey, @pmtKey, @productKey, @invFinEntityKey,@transDate,
                    @journalType,@invFiscalPeriod,
                    @glTypeDueToDueFrom,'DueFrom', null, null, null, @sequenceNumberDTDF,
                    @originatingBatchNumber, @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
                    SET @sequenceNumberDTDF = @sequenceNumberDTDF + 1


                END
            END
        END
    END
    IF UPPER(@postingData) = 'INVOICES' AND ISNULL(@appliedAmt,0) > 0
        AND @unearnedIncomeRecorded = 0
    BEGIN
        /* Unearned income: */
        /* Debit Unearned income liability account in sales journal */
        SET @amount = @appliedAmt
        EXEC asi_CreateTempGL @unearnedIncAcctKey,@amount,@invoiceKey, @pmtKey, @productKey,@paymentFinEntityKey, @transDate,
        @journalType, @pmtFiscalPeriod,
        @glTypeUnearnedIncome,'Unearned Income', null, null, null, @sequenceNumberUI, @originatingBatchNumber,
        @finalBatchNumber, @billToContactKey, @journalEntryDescription, @invoiceLineNumber
        SET @sequenceNumberUI = @sequenceNumberUI + 1
            
    END
    SET @previousDistFinEntityKey = @distFinEntityKey

    SET @previousInvFinEntityKey = @invFinEntityKey
    SET @previousPmtFinEntityKey = @paymentFinEntityKey
    SET @prevInvoiceDistKey = @invoiceDistKey
    SET @previousARAcctKey = @ARAcctKey
    SET @previousExtIncome = @extIncome
    SET @previousProductKey = @productKey
    SET @previousTransDate = @transDate
    set @prevInvoiceLineNumber = @invoiceLineNumber
    SET @prevBillToContactKey = @billToContactKey
    SET @prevInvoiceKey = @invoiceKey
    SET @prevJournalEntryDescription =  @journalEntryDescription
    SET @prevOriginatingBatchNumber = @originatingBatchNumber
    SET @prevFinalBatchNumber = @finalBatchNumber
    SET @accumAppliedAmt = ISNULL(@accumAppliedAmt,0) + ISNULL(@appliedAmt,0)
    next_record:
    FETCH next from GetInvoiceDistribution into @invoiceKey, @invoiceLineKey, @invoiceDistKey, @acctMethod,
    @invFinEntityKey, @distFinEntityKey, @extIncome, @extIncomeRecog, @incomeAcctKey, @ARAcctKey, @deferredIncAcctKey,
    @pmtAmt, @appliedAmt, @pmtKey, @transDate, @paymentFinEntityKey, @discountTaken, @deferralTermsKey, @sourceCodeKey,
    @invType, @batchItemStatus, @orderTypeKey, @responseMediaCode, @priceSheetKey, @warehouseKey, @genSalesHistory, @extendedCost,
    @orderNumber, @orderTypeKey, @orderDate, @billToContactKey, @shipToContactKey,
    @soldToContactKey, @productKey, @undiscountedExtendedPrice, @uomKey, @quantitySold, @commissionPlanKey, @salesTeamGroupKey,
    @salesLocationKey, @isPledge, @invoiceLineNumber, @invoiceNumber, @journalEntryDescription, @originatingBatchNumber, @finalBatchNumber
    /* Now create AR for the unpaid balance on the last distribution line if appropriate... */
    IF UPPER(@postingData) = 'INVOICES' AND
       UPPER(@acctMethod) = 'A' AND
       ABS(@previousExtIncome) > @accumAppliedAmt
       AND (@invoiceDistKey != @prevInvoiceDistKey OR @@FETCH_STATUS != 0)
    BEGIN
        SET @arAmount = @previousExtIncome - @accumAppliedAmt
        /* AR: */
        /* Debit AR asset account in sales journal */
        SET @amount = @arAmount
        EXEC asi_CreateTempGL @previousARAcctKey,@amount,@prevInvoiceKey, null, @previousProductKey, @previousInvFinEntityKey, @previousTransDate,
        @journalType, @invFiscalPeriod,
        @glTypeAccountsReceivable,'AR', null, null, null, @sequenceNumberAR, @prevOriginatingBatchNumber,
        @prevFinalBatchNumber, @prevBillToContactKey, @prevJournalEntryDescription, @prevInvoiceLineNumber
        SET @sequenceNumberAR = @sequenceNumberAR + 1


        /* DueToDueFrom: */
        IF @previousDistFinEntityKey != @previousInvFinEntityKey
        BEGIN
            SELECT @dueFromAcctKey = FromFinEntityGLAccountKey, @dueToAcctKey = ToFinEntityGLAccountKey
            FROM @duetoduefrom WHERE FromFinancialEntityKey = @previousInvFinEntityKey
            AND ToFinancialEntityKey = @previousDistFinEntityKey
    
            IF @dueFromAcctKey is not null AND @dueToAcctKey is not null
            BEGIN
                /* Credit DueTo account in sales journal */
                SET @amount = @arAmount * -1
                EXEC asi_CreateTempGL @dueFromAcctKey,@amount,@prevInvoiceKey, @pmtKey, @previousProductKey, @previousInvFinEntityKey, @previousTransDate,
                @journalType, @invFiscalPeriod,
                @glTypeDueToDueFrom,'DueTo', null, null, null, @sequenceNumberDTDF, @prevOriginatingBatchNumber,
                @prevFinalBatchNumber, @prevBillToContactKey, @prevJournalEntryDescription, @prevInvoiceLineNumber
                SET @sequenceNumberDTDF = @sequenceNumberDTDF + 1

                /* Debit DueFrom account in sales journal */
                SET @amount = @arAmount
                EXEC asi_CreateTempGL @dueToAcctKey,@amount,@prevInvoiceKey, @pmtKey, @previousProductKey, @previousDistFinEntityKey, @previousTransDate,
                @journalType, @distFiscalPeriod,
                @glTypeDueToDueFrom,'DueFrom', null, null, null, @sequenceNumberDTDF, @prevOriginatingBatchNumber,
                @prevFinalBatchNumber, @prevBillToContactKey, @prevJournalEntryDescription, @prevInvoiceLineNumber
                SET @sequenceNumberDTDF = @sequenceNumberDTDF + 1


            END
        END
    END
END
CLOSE GetInvoiceDistribution
DEALLOCATE GetInvoiceDistribution
/* Now, group the transaction lines by source item type and financial unit, */
/* creating a transaction for each distinct combination, insert the */
/* associated transaction lines. */
SELECT @tstCount = count(*) from #tmpTransLine

/* Create one or more temporary transactions. */
/* first for Invoice journal entries... */
INSERT #tmpTransaction(InvoiceKey,  FinEntityKey, TransDate, JournalEntryTypeCode, FiscalPeriod, Description,
    FinalBatchNumber, OriginatingBatchNumber, ContactKey)
SELECT DISTINCT InvoiceKey, FinEntityKey, TransDate, JournalEntryTypeCode, FiscalPeriod,
    MAX(JournalEntryDescription), MAX(FinalBatchNumber), MAX(OriginatingBatchNumber), BillToContactKey
FROM #tmpTransLine
WHERE (JournalEntryTypeCode = @journalTypeInvoice
  OR JournalEntryTypeCode = @journalTypeCreditInv
  OR JournalEntryTypeCode = @journalTypeDebitInv)
GROUP BY InvoiceKey, FinEntityKey, TransDate, JournalEntryTypeCode, FiscalPeriod,
    BillToContactKey

/* then for payment journal entries... */
INSERT #tmpTransaction(PaymentKey,  FinEntityKey, TransDate, JournalEntryTypeCode, FiscalPeriod, Description,
    FinalBatchNumber, OriginatingBatchNumber, ContactKey)
SELECT DISTINCT #tmpTransLine.PaymentKey, FinEntityKey, MIN(TransDate), @journalTypePayment, FiscalPeriod,
     MAX(JournalEntryDescription), MAX(FinalBatchNumber), MAX(OriginatingBatchNumber), BillToContactKey
FROM #tmpTransLine
WHERE JournalEntryTypeCode = @journalTypePayment
GROUP BY PaymentKey, FinEntityKey, TransDate, FiscalPeriod,  BillToContactKey

/* Create the real Journal Entry rows */
INSERT GLTransactionMain(GLTransactionKey, InvoiceKey, PaymentKey, TransactionDate, FinancialEntityKey,
                    JournalEntryTypeCode, FiscalPeriod, CreatedOn, Description,
                    FinalBatchNumber, OriginatingBatchNumber, ContactKey)
SELECT TransactionKey, InvoiceKey, PaymentKey, TransDate, FinEntityKey,
                    JournalEntryTypeCode, FiscalPeriod, getdate(), Description, FinalBatchNumber,
                    OriginatingBatchNumber, ContactKey
FROM #tmpTransaction


DECLARE Get_TempTransactions cursor for
    SELECT #tmpTransaction.TransactionKey, #tmpTransaction.JournalEntryTypeCode
    FROM  #tmpTransaction

OPEN Get_TempTransactions    
FETCH NEXT FROM Get_TempTransactions into @transKey, @journalType
WHILE @@FETCH_STATUS = 0
BEGIN    
    IF @journalType = @journalTypePayment
    BEGIN
        SET @sequenceNumber = 0
        /* First, do the cash line (probably one) */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeCash
        
        /* now, early payment discount lines */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeEarlyPaymentDiscount
        
        /* now, unearned income credit lines (probably one) */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber,  @glTypeUnearnedIncome
        
        /* now, unearned income debit lines ??*/
        
        /* Debit AR lines -- this in case of Accrual-based invoice */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeAccountsReceivable
        
        /* Credit Distribution lines -- this in case of cash-based invoice*/
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeDistribution
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeDeferredIncome
        
        /* now, DueTo/DueFrom */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeDueToDueFrom
    END
    ELSE
    BEGIN
        SET @sequenceNumber = 0
        
        /* First, do the distribution lines */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeDistribution
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeDeferredIncome
        
        /* now, unearned income debit lines */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber,  @glTypeUnearnedIncome
        
        /* now, AR credit lines */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeAccountsReceivable
        
        /* now, early payment discount lines */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeEarlyPaymentDiscount
        
        /* now, DueTo/DueFrom */
        EXEC @sequenceNumber = asi_WriteGLTransactionLines @transKey, @sequenceNumber, @glTypeDueToDueFrom
    END
    FETCH NEXT FROM Get_TempTransactions into @transKey, @journalType
END

GO
Uses
Used By